package view;

import javax.swing.*;
import java.awt.event.*;
import java.io.IOException;

import data.RecordOrShowRecord;

public class Record extends JDialog implements ActionListener {
    int time = 0;
    String grade = null;
    String key = null;
    String message = null;
    JTextField textName;
    JLabel label = null;
    JButton confirm, cancel;

    public Record() {
        setTitle("记录你的成绩");
        this.time = time;
        this.grade = grade;
        setBounds(100, 100, 240, 160);
        setResizable(false);
        setModal(true);
        confirm = new JButton("确定");
        cancel = new JButton("取消");
        textName = new JTextField(8);
        textName.setText("匿名");
        confirm.addActionListener(this);
        cancel.addActionListener(this);
        setLayout(new java.awt.GridLayout(2, 1));
        label = new JLabel("输入您的大名看是否可上榜");
        add(label);
        JPanel p = new JPanel();
        p.add(textName);
        p.add(confirm);
        p.add(cancel);
        add(p);
        setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }

    public void setTime(int time) {
        this.time = time;
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == confirm) {
            String name = textName.getText();
            try {
                writeRecord(name, time);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            setVisible(false);
        }
        if (e.getSource() == cancel) {
            setVisible(false);
        }
    }

    public int gradeId(String s) {
        if (s.equals("初级")) return 0;
        else if (s.equals("中级")) return 1;
        return 2;
    }

    public void writeRecord(String name, int time) throws IOException {
        RecordOrShowRecord rd = new RecordOrShowRecord();
        rd.setTable(grade);
        boolean boo = rd.addRecord(gradeId(grade), name, time);
        if (boo) {
            JOptionPane.showMessageDialog
                    (null, "恭喜您，上榜了", "消息框", JOptionPane.WARNING_MESSAGE);
        } else {
            JOptionPane.showMessageDialog
                    (null, "成绩不能上榜", "消息框", JOptionPane.WARNING_MESSAGE);
        }
    }
}
